package com.springboot.controller;

import com.springboot.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@Slf4j
public class UploadController {
    //处理转发用户注册-可以完成文件上传页面
    @RequestMapping("/upload.html")
    public String uploadPage() {
        return "upload";
    }
    //处理用户的注册请求

    /**
     * @param name
     * @param email
     * @param age
     * @param job
     * @param header MultipartFile这个类型可以接收文件
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("name") String name,
                         @RequestParam("email") String email,
                         @RequestParam("age") Integer age,
                         @RequestParam("job") String job,
                         @RequestParam("header") MultipartFile header,
                         @RequestParam("photos") MultipartFile[] photos) throws IOException {
        //输出获取到的信息
        log.info("上传的信息: name={} email={} age={} job={} header={} photos={}", name, email, age, job, header, photos);
        //信息核对成功之后，我们将文件保存到指定的目录，比如f:\\temp_upload
        //我们后面再将文件保存到动态创建的目录F:\Java\zjb_springboot\springboot-Thymrleaf\target\classes\static\images
        //1.首先得到类路径
        String path = ResourceUtils.getURL("classpath:").getPath();
//        log.info("path={}", path);
        //2.创建目录
        File file = new File(path + WebUtils.getUploadFileDirectory());
        if (!file.exists()) {//如果目录不存在，我们就创建
            file.mkdirs();
        }
        //3.
        if (!header.isEmpty()) {//处理头像
            //先拿到上传的文件名
            String filename = header.getOriginalFilename();
            String fname= UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+filename;
//            header.transferTo(new File("f:\\temp_upload\\header\\"+filename));
            header.transferTo(new File(file.getAbsolutePath() + "/" + fname));
        }
        if (photos.length > 0) {//至少一张图片才走
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    //先取文件名，后面会拼接的
                    String filename = photo.getOriginalFilename();
                    String fname= UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+filename;
                    // header.transferTo(new File("f:\\temp_upload\\pet\\"+filename));
                    photo.transferTo(new File(file.getAbsolutePath() + "/" + fname));
                }
            }
        }
        return "注册用户成功/文件上传成功";
    }
}
